<template>
  <div class="trendpad">
    <!-- -->
    <div id="trendpad-echarts" class="content" ></div>
    <div class="footer">
      <!-- <div style="margin-left: 10px">
        Page:
        <el-button @click="clickPrevious">&lt;</el-button>
        <el-button @click="clickNext">&gt;</el-button>
      </div>-->
      <!-- <div class="footer-item">
                Axis:
                <el-select v-model="form.region" placeholder="Please Select">
                    <el-option label="1 week" value="1"></el-option>
                    <el-option label="2 week" value="2"></el-option>
                </el-select>
      </div>-->
      <div class="footer-item" >
        Start:
        <el-date-picker :clearable="false" v-model="form.startTime" type="datetime" placeholder="Please enter"
          :disabled-date="disabledStartDate" :disabled="form.endTime && form.startTime > form.endTime"
          @change="changeStartTime"></el-date-picker>
      </div>
      <div class="footer-item" >
        End:
        <el-date-picker :clearable="false" v-model="form.endTime" type="datetime" placeholder="Please enter"
          :disabled="form.startTime && form.endTime < form.startTime" @change="changeEndTime"></el-date-picker>
      </div>
      <div class="footer-item">
        Switching Well:
        <el-select v-model="form.wellidname" placeholder="Please Select" @change="changeWellPad">
          <el-option v-for="(item, index) in fontValue" :key="index" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </div>
      <!-- <div class="footer-item">
                Update(s):
                <el-input
                    v-model="form.update"
                    placeholder="Please enter"
                ></el-input>
      </div>-->
      <div class="footer-item" style="width: 30%">
        <el-button type="primary" @click="clickCheck">Search</el-button>
        <el-button type="primary" @click="exportCheck" :loading="exportLoading" style="width: 5rem;">Export</el-button>
        <el-button type="primary" @click="openDialog">Config</el-button>
        <el-button type="primary" @click="clearMarks">Clear Marks</el-button>

      </div>
    </div>
    <div class="export_daochu" v-if="exportdaochu == true" v-loading="loading" element-loading-text="Export is Loading">
      Export is loading</div>
    <el-dialog v-model="dialogVisible" title="Config" width="110rem" :before-close="handleClose" :close-on-click-modal="false">
      <div class="tagConfigurationBox">
        <div class="left-box">
          <div>
            <div class="searchBar">
              <el-input placeholder="Tag Name Or Description" v-model="getAllTagPrarms.keyword"></el-input>
              <el-button type="primary" @click="getAllTagByKeywordFun">Search</el-button>
            </div>
            <div class="tip-box">Double Click Each Row to Add New Tag</div>
            <div class="left-list-box">
              <el-table :data="allTagNameList" border stripe :header-cell-style="{ 'text-align': 'center' }"
                height="100%" @row-dblclick="copyRowToRight">
                <el-table-column prop="tagName" show-overflow-tooltip label="Tag Name" align="left" width="210">
                </el-table-column>
                <el-table-column prop="unit" label="Unit" align="center" show-overflow-tooltip
                  width="80"></el-table-column>
                <el-table-column prop="remark" show-overflow-tooltip label="Desc" align="left"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="right-box">
          <div class="operationBar">
            <div> <el-button type="primary" @click="submitForm">Commit</el-button></div>
          </div>
          <div class="tip-box">Double Click Each Row to Delete Tag Name</div>
          <div class="right-list-box">
            <el-table :data="storedConfigs" border stripe :header-cell-style="{ 'text-align': 'center' }"
              class="compact-table" height="100%" @row-dblclick="dblDeleteItem">
              <el-table-column label="Color" align="center" width="70">
                <template #default="scope">
                  <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
                    <el-color-picker v-model="scope.row.color"></el-color-picker>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="tagName" show-overflow-tooltip label="Tag Name" align="center" width="210">
                <template #default="scope">
                  <div style="display: flex; justify-content: left; align-items: center; height: 100%;">
                    {{ scope.row.tagName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Trend Name" align="center">
                <template #default="scope">
                  <div style="display: flex; justify-content: left; align-items: center; height: 100%;">
                    <el-input v-if="scope.row.isNew" v-model="scope.row.trendName" size="mini"
                      @blur="makeTrendNameStatic(scope.$index)" placeholder="Please Enter"></el-input>
                    <span v-else>{{ scope.row.trendName || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="Unit" align="center" show-overflow-tooltip
                width="80"></el-table-column>
              <el-table-column prop="description" show-overflow-tooltip label="Desc" align="left"></el-table-column>
              <el-table-column prop="axes" label="Axes" align="center" width="400" style="padding: 0;">
                <template #default="scope">
                  <div class="groupItem gapR">
                    <div class="axesName ">Top:</div>
                    <el-radio-group v-model="scope.row.axes" size="mini">
                      <el-radio-button v-for="item in axesoOptions1" :key="item.value" :label="item.value"
                        style="padding: 0;margin: 0">{{ item.label }}</el-radio-button>
                    </el-radio-group>
                  </div>
                  <div class="groupItem">
                    <div class="axesName">Bottom:</div>
                    <el-radio-group v-model="scope.row.axes" size="mini">
                      <el-radio-button v-for="item in axesoOptions3" :key="item.value" :label="item.value"
                        style="padding: 0;margin: 0">{{ item.label }}</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="page-box">
        <custom-pagination style="text-align: left; justify-content: flex-start" :total="total" :page-count="pageCount"
          :current="currentPage" @pagination="handlePagination"></custom-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CustomPagiation from "@/components/customPagiation.vue";
import * as echarts from "echarts";
import {
  getTrendByTagType,
  exportEspTrend,
  getWellTag,
  setWellTrendConfig,
  getWellTrendConfig,
  getAllWellTag,
  getTrendOnlyByTagName,
  getAllTagByKeyword,
} from "@/api/index";
import { exportFile , deepClone} from "@/utils/common";
// TODO使用mqtt 进行优化
// import socket from "@/utils/websocket";
export default {
  name: "trendPad",
  components: { 'custom-pagination': CustomPagiation },
  props: {
    wellIdnumber: {
      type: String,
      default: ""
    },
    list: {
      type: Array,
      default: () => { }
    },
    padname: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      show:true,
      currentPage: 1,
      total: 0,
      pageCount: 0,
      axesoOptions1: [
        {
          value: 'ESP-1',
          label: 'Left'
        },
        {
          value: 'ESP-2',
          label: 'Right'
        }],
      axesoOptions3: [
        {
          value: 'ESP-3',
          label: 'Left'
        },
        {
          value: 'ESP-4',
          label: 'Right'
        }],
      allTagNameList: [],
      getAllTagPrarms: {
        keyword: "",
        page: 1,
        pageSize: 15
      },
      form_two: {
        color: "",
        trendName: "",
        tagName: "",
        axes: "",
      },
      storedConfigs: [],
      dialogVisible: false,
      form: {
        wellidname: '',
        exportdaochu: false,
        region: "",
        startTime: "",
        endTime: this.convertBeijingToCalgary(new Date()),
        interval: "3",
        update: ""
      },
      mychart2: "",
      wellId: this.wellIdnumber,
      splitTimes: [],
      htmlInfo:'',
      option: {
        title: [
          {
            x: "left",
            textStyle: {
              color: "rgba(219, 230, 255, 1)",
              fontSize: 16,
              fontWeight: "normal"
            },
            top: "2%",
            left: 10
          },
          {
            x: "left",
            textStyle: {
              color: "rgba(219, 0, 255, 1)",
              fontSize: 16,
              fontWeight: "normal"
            },
            top: "47%",
            left: 10
          }
        ],
        dataZoom: [
          {
            type: "inside",
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            zoomLock: true,
            showDataShadow: false,
            xAxisIndex: [0, 1]
          },
          {
            type: "slider",
            realtime: true,
            start: 0,
            end: 100,
            showDataShadow: false,
            textStyle: {
              color: "white"
            },
            bottom: "2%",
            borderColor: "#43485E",
            dataBackground: {
              areaStyle: {
                color: "white"
              }
            }
          }
        ],
        backgroundColor: "#1B232E",
        tooltip: {
          trigger: "axis",
          // link: [
          //   {
          //     xAxisIndex: 'all'
          //   }
          // ],
          axisPointer: {
            link: [
              {
                xAxisIndex: 'all',
              }
            ],
            animation: false
          },
          formatter: params=> {
            let showHtml = '';
            // 获取 x 轴的值
            let xAxisValue = params[0].axisValueLabel;
            // 显示 x 轴的值
            showHtml += `<div style="text-align: left;">${xAxisValue}</div>`;
            const seenSeriesNames = {}; // 用于记录已经出现过的 seriesName
            for (let i = 0; i < params.length; i++) {
              let value = params[i].value;
              let seriesName = params[i].seriesName;
              // 检查 seriesName 是否已经出现过
              if (seenSeriesNames[seriesName]) {
                continue; // 如果已经出现过，跳过当前项
              }
              // 标记该 seriesName 已经出现过
              seenSeriesNames[seriesName] = true;
              let itemHtml = '';
              // 检查值是否为空字符串
              if (value === '') {
                // 如果是空字符串，使用红色字体显示
                itemHtml = `${params[i].marker}<span style="color:red;">${seriesName}: NaN</span>`;
              } else {
                // 如果不是空字符串，正常显示
                itemHtml = `${params[i].marker}${seriesName}: ${value}`;
              }
              // 将每个数据项用 div 包裹并设置左对齐
              showHtml += `<div style="text-align: left;">${itemHtml}</div>`;
            }
            this.htmlInfo = showHtml

            return showHtml;
          },
          textStyle: {
            color: "rgba(255, 255, 255, 1)",
            align: "left"
          },
          backgroundColor: "rgba(0,0,0,0.8)",
          borderColor: "rgba(219, 230, 255, 0.8)"
        },
        axisPointer: {
          link: {
            xAxisIndex: "all"
          }
        },
        color: [
          "rgba(251, 210, 0, 1)",
          "rgba(250, 109, 62, 1)",
          "rgba(240, 244, 255, 1)"
        ],
        legend: [
          {
            data: [],
            x: "left",
            formatter: function (name) {
              const hasNoData = name.includes('No data');
              if (hasNoData == true) {
                return '{a|' + name + '}';
              } else {
                return '{b|' + name + '}';
              }
            },
            textStyle: {
              rich: {
                a: {
                  color: 'red',
                  fontSize: 14
                },
                b: {
                  color: 'white',
                  fontSize: 14
                },
              }
            },
            top: "2.5%",
            right: 30,
            left: 30,
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 5 // 缩小图例项之间的间距
          },
          {
            data: [],
            x: "right",
            formatter: function (name) {
              const hasNoData = name.includes('No data');
              if (hasNoData == true) {
                return '{a|' + name + '}';
              } else {
                return '{b|' + name + '}';
              }
            },
            textStyle: {
              rich: {
                a: {
                  color: 'red',
                  fontSize: 14
                },
                b: {
                  color: 'white',
                  fontSize: 14
                },
              }
            },
            top: "2.5%",
            right: 30,
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 5 // 缩小图例项之间的间距
          },
          {
            data: [],
            x: "left",
            formatter: function (name) {
              const hasNoData = name.includes('No data');
              if (hasNoData == true) {
                return '{a|' + name + '}';
              } else {
                return '{b|' + name + '}';
              }
            },
            textStyle: {
              rich: {
                a: {
                  color: 'red',
                  fontSize: 14
                },
                b: {
                  color: 'white',
                  fontSize: 14
                },
              }
            },
            top: "66%",
            right: 30,
            left: 30,
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 5 // 缩小图例项之间的间距
          },
          {
            data: [],
            x: "right",
            formatter: function (name) {
              const hasNoData = name.includes('No data');
              if (hasNoData == true) {
                return '{a|' + name + '}';
              } else {
                return '{b|' + name + '}';
              }
            },
            textStyle: {
              rich: {
                a: {
                  color: 'red',
                  fontSize: 14
                },
                b: {
                  color: 'white',
                  fontSize: 14
                },
              }
            },
            top: "66%",
            right: 30,
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 5 // 缩小图例项之间的间距
          }
        ],
        grid: [
          {
            left: "50px",
            right: "30px",
            top: "7%",
            height: "64%",
            containLabel: true
          },
          {
            left: "55px",
            right: "47px",
            top: "70%",
            height: "23%",
            containLabel: true
          }
        ],
        xAxis: [
          {
            type: "category",
            boundaryGap: ["20%", "20%"],
            axisLabel: {
              formatter: function (value) {
                let res = ""; // 拼接加\n返回的类目项
                let maxLength = 10; // 每项显示文字个数  数字设置几，就一行显示几个文字
                let valLength = value.length; // X轴上的文字个数
                let rowN = Math.ceil(valLength / maxLength); // 需要换行的行数
                // 换行的行数大于1,
                if (rowN > 1) {
                  for (let i = 0; i < rowN; i++) {
                    let temp = ""; //每次截取的字符串
                    let start = i * maxLength; //开始截取的位置
                    let end = start + maxLength; //结束截取的位置
                    temp = value.substring(start, end) + "\n";
                    res += temp; //拼接字符串
                  }
                  return res;
                } else {
                  return value;
                }
              },
              color: "#A9AEB2",
              fontSize: 12,
              interval: 330, // 每隔两个标签显示一个
              showMaxLabel: true, // 确保显示最大值标签
              showMinLabel: true // 确保显示最小值标签
            },
            show: false,
            axisTick: {
              show: false
            },
            axisLine: {
              onZero: true,
              lineStyle: {
                color: "#515773"
              }
            },
            data: []
          },
          {
            gridIndex: 1,
            boundaryGap: ["20%", "20%"],
            type: "category",
            axisLabel: {
              formatter: function (value) {
                let res = ""; // 拼接加\n返回的类目项
                let maxLength = 10; // 每项显示文字个数  数字设置几，就一行显示几个文字
                let valLength = value.length; // X轴上的文字个数
                let rowN = Math.ceil(valLength / maxLength); // 需要换行的行数
                // 换行的行数大于1,
                if (rowN > 1) {
                  for (let i = 0; i < rowN; i++) {
                    let temp = ""; //每次截取的字符串
                    let start = i * maxLength; //开始截取的位置
                    let end = start + maxLength; //结束截取的位置
                    temp = value.substring(start, end) + "\n";
                    res += temp; //拼接字符串
                  }
                  return res;
                } else {
                  return value;
                }
              },
              color: "#A9AEB2",
              fontSize: 12,
              interval: 330, // 每隔两个标签显示一个
              showMaxLabel: true, // 确保显示最大值标签
              showMinLabel: true // 确保显示最小值标签
            },
            show: true,
            axisTick: {
              show: false
            },
            axisLine: {
              onZero: true,
              lineStyle: {
                color: "#515773"
              }
            },
            data: []
          }
        ],
        yAxis: [
          {
            type: "value",
            // name: 'Trend 1',
            // nameRotate: 90,
            // nameLocation: 'middle',
            // nameGap: 35,
            min: 0,
            splitNumber: 9,
            axisLabel: {
              color: "#A9AEB2",
              fontSize: 12,
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: "#515773"
              }
            },
            nameTextStyle: {
              color: "#A9AEB2",
              fontSize: "14"
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#43485E"],
                width: 1,
                type: "solid"
              }
            }
          },
          {
            type: "value",
            min: 0,
            // name:'Trend 2',
            // nameRotate: 90,
            // nameLocation: 'middle',
            // nameGap: 50,
            splitNumber: 9,
            axisLabel: {
              color: "#A9AEB2",
              fontSize: 12
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: "#515773"
              }
            },
            nameTextStyle: {
              color: "#A9AEB2",
              fontSize: "14"
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#43485E"],
                width: 1,
                type: "solid"
              }
            }
          },
          {
            gridIndex: 1,
            max: 40,
            min: 0,
            // name:'Trend 3',
            // nameRotate: 90,
            // nameLocation: 'middle',
            // nameGap: 35,
            splitNumber: 10,
            type: "value",
            axisLabel: {
              color: "#A9AEB2",
              fontSize: 12
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#515773"
              }
            },
            nameTextStyle: {
              color: "#A9AEB2",
              fontSize: "14"
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: ["#43485E"],
                width: 1,
                type: "solid"
              }
            }
          },
          {
            gridIndex: 1,
            max: 50,
            min: 0,
            // name:'Trend 4',
            // nameRotate: 90,
            // nameLocation: 'middle',
            // nameGap: 35,
            splitNumber: 10,
            type: "value",
            axisLabel: {
              color: "#A9AEB2",
              fontSize: 12
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#515773"
              }
            },
            nameTextStyle: {
              color: "#A9AEB2",
              fontSize: "14"
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#43485E"],
                width: 1,
                type: "solid"
              }
            }
          }
        ],
        series: []
      },
      axesoOptions: [
        {
          value: 'top left',
          label: 'left'
        },
        {
          value: 'top right',
          label: 'right'
        }, {
          value: 'bottom left',
          label: 'bottom left'
        },
        {
          value: 'bottom right',
          label: 'bottom right'
        },
      ],
      lineColor: [
        '#fe7501', '#00d4fa', '#f371ff', '#4ad400', '#bb1504', '#31adf3', '#0345e3',
        '#9ce6fd', '#868ecb', '#f90aaf', '#f9cdd8',
        '#fc7298', '#5a91f5', '#b6e959', '#4ec4d6',
        '#fed505', '#f59f83', '#a00386', '#5b63ff', '#b29bc3', '#7de7a2', '#fec503'],
      xData: [],
      xValue: [],
      exportLoading: false,
      xInterval: "",
      loading: false,
      myChart: null,
      tagList: [],
      options: [], // 初始化为空数组
      paginatedOptions: [],
      pageSize: 100,
      loading_two: false,
      filteredOptions: [],
      fontValue: [],
      nametitletwo: [],
      rich:{}
    };
  },
  created() {
    let endTime = "";
    if (this.isDateObject(this.form.endTime)) {
      endTime = this.formatDate(this.form.endTime);
    } else {
      endTime = this.form.endTime;
    }
    this.calculateTime(endTime, "day14", "0");
  },
  mounted() {
    this.listValueop();
    this.allTags();
    this.getWellTrendConfig()
    window.addEventListener("resize", this.handleChartResize);
  },
  //   beforeDestroy() {
  //     window.removeEventListener("resize", this.handleChartResize);
  //   },

  methods: {
    clearMarks(){
      this.clickCheck()

    },
    //双击删除一条并更新echarts
    dblDeleteItem(row) {
      this.storedConfigs.forEach((item, index) => {
        if (item.tagName === row.tagName) {
          this.storedConfigs.splice(index, 1)
        }
      })
      this.option.series = this.option.series.filter(series => series.name !== row.trendName);
      // 从 legend 中移除对应的项
      this.option.legend.forEach(legend => {
        const legendIndex = legend.data.indexOf(row.trendName);
        if (legendIndex > -1) {
          legend.data.splice(legendIndex, 1);
        }
      });
      // 如果所有系列都被删除，清空 xAxis.data
      if (this.option.series.length === 0) {
        this.option.xAxis[0].data = [];
        this.option.xAxis[1].data = [];
      }
      // 重新初始化 ECharts
      this.init();
    },
    // 模糊查询全部tagName
    getAllTagByKeywordFun() {
      getAllTagByKeyword(this.getAllTagPrarms).then(res => {
        if (res.code === 200) {
          this.total = res.data.total
          this.getAllTagPrarms.page = res.data.page
          this.getAllTagPrarms.pageSize = res.data.pageSize
          this.allTagNameList = res.data.records
          this.pageCount = res.data.pages
        } else {
          return this.$message.error(res.msg);
        }
      })
    },
    handlePagination(pagination) {
      this.getAllTagPrarms.pageSize = pagination.pageSize
      this.getAllTagPrarms.page = pagination.page
      this.currentPage = pagination.page
      this.getAllTagByKeywordFun()
    },
    //随机颜色生成
    getRandomHexColor() {
      let dataList = this.storedConfigs || []
      if (dataList.length < 22) {
        return this.lineColor[dataList.length]
      } else {
        // 生成更鲜艳的 #RRGGBB 格式随机颜色
        // 生成鲜艳明亮的 #RRGGBB 格式随机颜色
        const r = Math.floor(Math.random() * 128) + 128; // 红色分量 128-255
        const g = Math.floor(Math.random() * 128) + 128; // 绿色分量 128-255
        const b = Math.floor(Math.random() * 128) + 128; // 蓝色分量 128-255
        // 转换为十六进制
        const toHex = (value) => value.toString(16).padStart(2, '0');
        return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
      }
    },
    convertAxes(axesValue) {
      switch (axesValue) {
        case 'top left':
          return 'ESP-1';
        case 'top right':
          return 'ESP-2';
        case 'bottom left':
          return 'ESP-3';
        case 'bottom right':
          return 'ESP-4';
        default:
          return axesValue; // 如果不匹配任何条件，返回原值
      }
    },
    copyRowToRight(row) {
      console.log(row, '双击时候左侧列表');
      if (this.storedConfigs.length == 20) {
        this.$message.info('Please double-click to delete and add data when the amount of data has reached 20 items.')
      } else {
        // 创建新的数据对象，添加isNew标记
        let data = {
          axes: this.convertAxes(),
          color: this.getRandomHexColor(),
          tagName: row.tagName,
          unit: row.unit,
          description: row.remark,
          trendName: '',        // 初始化trendName为空
          isNew: true           // 标记为新添加的数据
        };
        // 检查是否存在重复
        const isDuplicate = this.storedConfigs.some(
          item => item.tagName === data.tagName
        );
        if (isDuplicate) {
          this.$message.info("Duplicate Tag Names!")
          return;
        }
        // 将新数据添加到右侧数组中
        this.storedConfigs.push(data);
        // 触发重绘，确保输入框正确显示
        this.$nextTick(() => {
          const inputs = this.$el.querySelectorAll('el-input');
          if (inputs.length) {
            inputs[inputs.length - 1].focus(); // 聚焦到最后一个输入框
          }
        });
      }
    },
    // 使Trend Name变为静态文本
    makeTrendNameStatic(index) {
      this.$set(this.storedConfigs[index], 'isNew', false);
    },
    changeWellPad(item) {
      this.wellId = item;
      this.$emit('child-event', item);
      this.option.series = []
      this.option.length = [];
      this.getWellTrendConfig();
    },
    listValueop() {
      this.fontValue = [];
      this.list.forEach(item => {
        this.fontValue.push({
          label: item.wellShowName,
          id: item.id
        })
        if (item.wellShowName == this.padname) {
          this.form.wellidname = item.id
        }
      })
    },
    async allTags() {
      const res = await getAllWellTag();
      if (res.code == 200) {
        this.options = res.data.map(item => ({
          label: item.tagName,
          value: item.tagName
        }));
        this.filteredOptions = this.options;
        this.updatePaginatedOptions();
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.updatePaginatedOptions();
    },
    handleRemoteMethod(query) {
      if (query !== '') {
        this.loading_two = true;
        setTimeout(() => {
          this.filteredOptions = this.options.filter(item =>
            item.label.toLowerCase().includes(query.toLowerCase())
          );
          this.currentPage = 1; // Reset to first page
          this.updatePaginatedOptions();
          this.loading_two = false;
        }, 200);
      } else {
        this.filteredOptions = this.options;
        this.currentPage = 1; // Reset to first page
        this.updatePaginatedOptions();
      }
    },
    updatePaginatedOptions() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      this.paginatedOptions = this.filteredOptions.slice(start, end);
    },
    //取消
    calcelclick() {
      this.dialogVisible = false;
      this.getWellTrendConfig()
    },
    //获取井趋势图配置信息
    async getWellTrendConfig() {
      let formData = new FormData();
      formData.append('wellId', this.wellId);
      const res = await getWellTrendConfig(formData);
      if (res.code === 200) {
        this.cunchustoredConfigs = res.data.productionWellTrendConfigList;
        this.nametitletwo = [];
        this.cunchustoredConfigs.forEach(item => {
          this.nametitletwo.push(item.trendName)
        })
        const promises = res.data.productionWellTrendConfigList.map(item => {
          return this.getTrendByTagNamemethods(item.tagName, item.color, item.axes, item.trendName);
        });
        try {
          await Promise.all(promises);
          // 所有异步操作都完成后的回调
        } catch (error) {
          console.error('An error occurred while fetching trends:', error);
        }
      }
    },
    //下拉框接口
    async getTagselect() {
      const res = await getWellTag(this.wellId)
      if (res.code == 200) {
        this.tagList = [];
        res.data.forEach(item => {
          this.tagList.push({
            label: item.tagName,
            value: item.tagName
          })
        })
      }
    },
    async submitForm() {
      let data = {
        wellId: this.wellId,
        productionWellTrendConfigList: this.storedConfigs
      }
      const res = await setWellTrendConfig(data)
      if (res.code == 200) {
        this.dialogVisible = false;
        this.getWellTrendConfig()
        this.$message.success(res.msg)
      } else {
        this.$message.error(res.msg)
      }
    },
    tagnameMthods() {
      const promises = this.storedConfigs.map(item => {
        return this.getTrendByTagNamemethods(item.tagName, item.color, item.axes, item.trendName);
      });
      Promise.all(promises).then(() => {
        // 所有异步操作都完成后的回调
      }).catch(error => {
        console.error('An error occurred:', error);
      });
    },
    dealwith(color, axes, trendName, keys, values) {
      let xAxisIndex = 0;
      let yAxisIndex = 0;
      // 1. 解析axes对应的坐标轴索引
      switch (axes) {
        case "ESP-1":
          xAxisIndex = 0;
          yAxisIndex = 0;
          break;
        case "ESP-2":
          xAxisIndex = 0;
          yAxisIndex = 1;
          break;
        case "ESP-3":
          xAxisIndex = 1;
          yAxisIndex = 2;
          break;
        case "ESP-4":
          xAxisIndex = 1;
          yAxisIndex = 3;
          break;
      }
      // 2. 更新xAxis配置
      if (axes === 'ESP-1' || axes === 'ESP-2') {
        if (!this.option.xAxis[0]) {
          this.option.xAxis[0] = { type: 'category', data: [] };
        }
        this.option.xAxis[0].axisLabel.interval = Math.floor(values.length / 6);
        this.option.xAxis[1].axisLabel.interval = Math.floor(values.length / 6);
        this.option.xAxis[1].data = keys;
        this.option.xAxis[0].data = keys;
      } else {
        if (!this.option.xAxis[1]) {
          this.option.xAxis[1] = { type: 'category', data: [] };
        }
        this.option.xAxis[1].axisLabel.interval = Math.floor(values.length / 6);
        this.option.xAxis[1].data = keys;
      }
      // 3. 创建新系列
      const newSeries = {
        name: trendName,
        type: "line",
        emphasis: { focus: "series" },
        data: values,
        label: { show: false, color: "white" },
        lineStyle: {
          normal: { width: 1, color: color },
          emphasis: { color: color, width: 2 }
        },
        itemStyle: { color: color },
        symbol: "none",
        xAxisIndex: xAxisIndex,
        yAxisIndex: yAxisIndex,
      };
      // 4. 查找旧系列索引（若存在则替换，否则追加）
      const seriesIndex = this.option.series.findIndex(item => item.name === trendName);
      if (seriesIndex !== -1) {
        // 获取旧系列的axes信息，用于删除旧图例
        const oldSeries = this.option.series[seriesIndex];
        const oldAxes = this.getAxesByIndex(oldSeries.xAxisIndex, oldSeries.yAxisIndex);
        const oldLegendIndex = this.getLegendIndexByAxes(oldAxes);
        // 从旧图例中删除该系列
        if (oldLegendIndex !== -1 && this.option.legend[oldLegendIndex]) {
          const oldLegendData = this.option.legend[oldLegendIndex].data;
          const indexInOldLegend = oldLegendData.indexOf(trendName);
          if (indexInOldLegend !== -1) {
            oldLegendData.splice(indexInOldLegend, 1);
          }
        }
        // 替换旧系列
        this.option.series.splice(seriesIndex, 1, newSeries);
      } else {
        // 追加新系列
        this.option.series.push(newSeries);
      }
      // 5. 更新图例（关键修改：移除旧图例，只保留新位置的图例）
      let legendIndex = -1;
      switch (axes) {
        case "ESP-1": legendIndex = 0; break;
        case "ESP-2": legendIndex = 1; break;
        case "ESP-3": legendIndex = 2; break;
        case "ESP-4": legendIndex = 3; break;
      }
      // 确保legend存在并设置位置
      if (!this.option.legend[legendIndex]) {
        this.option.legend[legendIndex] = {
          data: [],
          textStyle: { color: "white", fontSize: 14 },
          itemWidth: 20,
          itemHeight: 10,
          itemGap: 20
        };
        // 根据ESP位置设置legend坐标
        switch (axes) {
          case "ESP-1":
            this.option.legend[legendIndex].top = "2.5%";
            this.option.legend[legendIndex].left = 30;
            break;
          case "ESP-2":
            this.option.legend[legendIndex].top = "2.5%";
            this.option.legend[legendIndex].right = 30;
            this.option.legend[legendIndex].x = "right";
            break;
          case "ESP-3":
            this.option.legend[legendIndex].top = "66%";
            this.option.legend[legendIndex].left = 30;
            this.option.legend[legendIndex].x = "left";
            break;
          case "ESP-4":
            this.option.legend[legendIndex].top = "66%";
            this.option.legend[legendIndex].right = 30;
            this.option.legend[legendIndex].x = "right";
            break;
        }
      }
      // 从其他所有图例中删除该系列（确保只在新位置显示）
      for (let i = 0; i < 4; i++) {
        if (i !== legendIndex && this.option.legend[i]) {
          const otherLegendData = this.option.legend[i].data;
          const indexInOtherLegend = otherLegendData.indexOf(trendName);
          if (indexInOtherLegend !== -1) {
            otherLegendData.splice(indexInOtherLegend, 1);
          }
        }
      }
      // 添加到新图例（如果不存在）
      const legendData = this.option.legend[legendIndex].data;
      if (!legendData.includes(trendName)) {
        legendData.push(trendName);
      }
      // 6. 刷新图表
      this.init();
      this.dialogVisible = false;
    },
    // 辅助方法：根据xAxisIndex和yAxisIndex获取对应的axes值
    getAxesByIndex(xIndex, yIndex) {
      if (xIndex === 0 && yIndex === 0) return "ESP-1";
      if (xIndex === 0 && yIndex === 1) return "ESP-2";
      if (xIndex === 1 && yIndex === 2) return "ESP-3";
      if (xIndex === 1 && yIndex === 3) return "ESP-4";
      return null;
    },
    // 辅助方法：根据axes获取对应的legend索引
    getLegendIndexByAxes(axes) {
      switch (axes) {
        case "ESP-1": return 0;
        case "ESP-2": return 1;
        case "ESP-3": return 2;
        case "ESP-4": return 3;
        default: return -1;
      }
    },
    async getTrendByTagNamemethods(tagName, color, axes, trendName) {
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      const res = await getTrendOnlyByTagName({
        startTime: this.form.startTime,
        endTime: endTime,
        tagName: tagName
      });
      if (res.code === 200) {
        let keys = [];
        let values = [];
        if (Object.keys(res.data.timeList).length === 0) {
          // 如果 timeList 为空对象，拼接 NOdata
          trendName = `${trendName} (No data)`;
        } else {
          const entries = Object.entries(res.data.timeList);
          entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
          const sortedData = Object.fromEntries(entries);
          keys = Object.keys(sortedData);
          values = Object.values(sortedData);
        }
        this.dealwith(color, axes, trendName, keys, values);
      }
    },
    //删除表单
    deleteConfig(index) {
      // 从 storedConfigs 中删除项
      const deletedConfig = this.storedConfigs.splice(index, 1)[0];
      // 从 option.series 中移除对应的系列
      this.option.series = this.option.series.filter(series => series.name !== deletedConfig.trendName);
      // 从 legend 中移除对应的项
      this.option.legend.forEach(legend => {
        const legendIndex = legend.data.indexOf(deletedConfig.trendName);
        if (legendIndex > -1) {
          legend.data.splice(legendIndex, 1);
        }
      });
      // 如果所有系列都被删除，清空 xAxis.data
      if (this.option.series.length === 0) {
        this.option.xAxis[0].data = [];
        this.option.xAxis[1].data = [];
      }
      // 重新初始化 ECharts
      this.init();
    },
    //弹窗打开
    openDialog() {
      this.dialogVisible = true;
      this.getAllTagPrarms.keyword = '';
      this.storedConfigs = this.cunchustoredConfigs;
      this.getAllTagByKeywordFun()
    },
    handleChartResize() {
      if (!this.myChart2) {
        return;
      }
      this.myChart2.resize();
    },

    // 初始化图标
    init() {

      var chartDom = document.getElementById("trendpad-echarts");
      this.myChart2 = echarts.init(chartDom);

      try {
        this.myChart2.clear()
      } catch (error) {
        console.log(error, 'ppppppppp')
      }
      let tooltipParams = [];
      // 存储当前缩放状态
      let currentZoom = {
        start: 0,
        end: 100
      };
      let option = this.option
      option.tooltip={
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        },
        showContent: true, // 是否显示详细信息
        formatter: function (params){
          tooltipParams = params;

            let showHtml = '';
            // 获取 x 轴的值
            let xAxisValue = params[0].axisValueLabel;
            // 显示 x 轴的值
            showHtml += `<div style="text-align: left;">${xAxisValue}</div>`;
            const seenSeriesNames = {}; // 用于记录已经出现过的 seriesName
            for (let i = 0; i < params.length; i++) {
              let value = params[i].value;
              let seriesName = params[i].seriesName;
              // 检查 seriesName 是否已经出现过
              if (seenSeriesNames[seriesName]) {
                continue; // 如果已经出现过，跳过当前项
              }
              // 标记该 seriesName 已经出现过
              seenSeriesNames[seriesName] = true;
              let itemHtml = '';
              // 检查值是否为空字符串
              if (value === '') {
                // 如果是空字符串，使用红色字体显示
                itemHtml = `${params[i].marker}<span style="color:red;">${seriesName}: NaN</span>`;
              } else {
                // 如果不是空字符串，正常显示
                itemHtml = `${params[i].marker}${seriesName}: ${value}`;
              }
              // 将每个数据项用 div 包裹并设置左对齐
              showHtml += `<div style="text-align: left;">${itemHtml}</div>`;
            }
            // self.htmlInfo = showHtml

            return showHtml;
        },
        textStyle: {
          color: "rgba(255, 255, 255, 1)",
          align: "left"
        },
        backgroundColor: "rgba(0,0,0,0.8)",
        borderColor: "rgba(219, 230, 255, 0.8)"
      }
      option.dataZoom = [
        {
          show: true,
          zoomOnMouseWheel: true,
          realtime: true,
          start: currentZoom.start,
          end: currentZoom.end,
          xAxisIndex: [0, 1, 2],
          height: 12,
          textStyle: {
            color: "#fff",
            fontSize: '0.7rem'
          },
          showDataShadow: false,
        },
        {
          type: 'inside',
          realtime: true,
          start: currentZoom.start,
          end: currentZoom.end,
          xAxisIndex: [0, 1, 2],
          showDataShadow: false,
        }
      ],
      option.series.forEach(item=>{
        item.connectNulls = true
        item.symbol='circle'
        item.markPoint = {
          symbol: "arrow",
          symbolSize:'5',
          data:[]
        }
      })


      this.option = option
      this.option && this.myChart2.setOption(this.option);


      // 监听dataZoom事件以保存当前缩放状态
      this.myChart2.on('datazoom', function(params) {
        if (params.batch) {
          currentZoom.start = params.batch[0].start;
          currentZoom.end = params.batch[0].end;
        } else {
          currentZoom.start = params.start;
          currentZoom.end = params.end;
        }
      });

      //点击添加详情
      let markLines = []
      let myCharts2 = echarts.init(chartDom)
      let self = this;

      myCharts2.on('click',function (params){
        let rich = {}
        tooltipParams.forEach((item,index)=>{
          rich[`item${index}`] = {
            color: item.color,
          };
        })

        let index1 = 0;
            if(params.seriesType === 'line'){
              let pointInPixel =[params.event.offsetX, params.event.offsetY];
              let seriesIndex = params.seriesIndex;
              let seriesOption = myCharts2.getOption().series[seriesIndex];
              let gridIndex = seriesOption.gridIndex;
              let pointInGrid = myCharts2.convertFromPixel({seriesIndex: 0}, pointInPixel);
              let dataIndex = pointInGrid[0]
              let dataIndexy = pointInGrid[1]

              let copyOption = deepClone(option)
              //存储线的位置
              let obj = {
                xAxis: dataIndex,
                lineStyle: {
                  color: '#FFFFFF',
                  width: 1,
                  type: 'dashed',
                },
                tooltipParams:tooltipParams,
                offsetX:dataIndex,
                offsetY:dataIndexy,
                value:params.value,
                name:params.seriesName
              }

              markLines.push(obj);

              copyOption.series.some((series,index)=>{
                series.markLine = {
                  label:{
                    formatter: '{b}',
                    show: true,
                    textStyle: {
                      color:'#fff'
                    },
                  },
                  silent: true, // 不触发事件
                  symbol: 'none', // 不显示箭头
                  data: markLines.map(line => ({
                    xAxis: line.xAxis,
                    lineStyle: line.lineStyle,
                    type:'line',
                  }))
                };

                if(series.name === params.seriesName && series.gridIndex === gridIndex){
                  index1 = index;//记录要设置数据的索引位置

                    let newPoint = {
                      coord:[dataIndex,params.value],
                      label:{
                        show:true,
                        formatter:()=>{
                          let pointarr = [];
                          markLines.map(point =>{
                            if(point.xAxis ===dataIndex && point.value === params.value){
                              point.tooltipParams.forEach((item,index)=>{

                                if(index === 0){
                                  pointarr.push(`${item.name}`)
                                }

                                pointarr.push(`{item${index}| • }${item.seriesName} : ${item.value}`)
                              })
                            }
                          })
                          return pointarr.join('\n')
                        },
                        rich: rich, // 注入动态生成的 rich
                        color: '#fff',
                        align:'left',
                        fontSize: 12,
                        lineHeight:18,
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        borderWidth:1,
                        borderColor: '#fff',
                        padding:5,
                        borderRadius:4
                      }
                    }
                    copyOption.series[index1].markPoint.data.push(newPoint)
                    copyOption.dataZoom[0].start = currentZoom.start
                    copyOption.dataZoom[0].end = currentZoom.end
                    option = copyOption

                }
              })

            }
        self.myChart2.setOption(option);
      })

    },

    disabledStartDate(time) {
      if (this.form.endTime) {
        return time.getTime() > new Date(this.form.endTime).getTime();
      }
      return false;
    },
    changeStartTime(item) {
      const date = new Date(item);
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      if (this.form.endTime && this.form.startTime > this.form.endTime) {
        this.form.startTime = this.form.endTime;
      }
    },
    changeEndTime(value) {
      if (this.form.startTime && this.form.endTime < this.form.startTime) {
        this.form.endTime = this.form.startTime;
      }
      //  let endTime = "";
      // if (this.isDateObject(this.form.endTime)) {
      //   endTime = this.formatDate(this.form.endTime);
      // } else {
      //   endTime = this.form.endTime;
      // }
      // if (this.form.interval == "0") {
      //   // 8小时
      //   this.calculateTime(endTime, "hour", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "1") {
      //   // 1天
      //   this.calculateTime(endTime, "day", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "2") {
      //   // 7天
      //   this.calculateTime(endTime, "day7", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "3") {
      //   // 14天
      //   this.calculateTime(endTime, "day14", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "4") {
      //   // 30天
      //   this.calculateTime(endTime, "day30", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else {
      //   // 60天
      //   this.calculateTime(endTime, "day60", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // }
    },
    changeInterval(value) {
      console.log(value, "interval");
      console.log(this.form.interval, "interval");
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      // 刚进页面 starttime为空或者null，endtime有值 选择interval时
      if (this.form.startTime == "" || this.form.startTime == null) {
        if (value == "0") {
          // 8小时
          this.calculateTime(endTime, "hour", "0");
          console.log(this.form.startTime, "this.form.startTime4444");
        } else if (value == "1") {
          // 1天
          this.calculateTime(endTime, "day", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "2") {
          // 7天
          this.calculateTime(endTime, "day7", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "3") {
          // 14天
          this.calculateTime(endTime, "day14", "0");
          console.log(this.form.startTime, "this.form.startTime9999");
        } else if (value == "4") {
          // 30天
          this.calculateTime(endTime, "day30", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else {
          // 60天
          this.calculateTime(endTime, "day60", "0");
        }
      }
      // 当清空endtime 选择starttime和interval时
      if (this.form.endTime == "" || this.form.endTime == null) {
        // if (value == "0") {
        //     // 1小时
        //     this.calculateTime(this.form.startTime, "hour", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else if (value == "1") {
        //     // 1天
        //     this.calculateTime(this.form.startTime, "day", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else if (value == "2") {
        //     // 1周
        //     this.calculateTime(this.form.startTime, "week", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else {
        //     // 1月
        //     this.calculateTime(this.form.startTime, "month", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // }
        if (value == "0") {
          // 8小时
          this.calculateTime(this.form.startTime, "hour", "0");
        } else if (value == "1") {
          // 1天
          this.calculateTime(this.form.startTime, "day", "0");
        } else if (value == "2") {
          // 7天
          this.calculateTime(this.form.startTime, "day7", "0");
        } else if (value == "3") {
          // 14天
          this.calculateTime(this.form.startTime, "day14", "0");
        } else if (value == "4") {
          // 30天
          this.calculateTime(this.form.startTime, "day30", "0");
        } else {
          // 60天
          this.calculateTime(this.form.startTime, "day60", "0");
        }
      }
      // 当开始时间和结束时间都不为空时，根据结束时间和天数计算开始时间
      if (this.form.endTime !== "" && this.form.startTime !== "") {
        if (value == "0") {
          // 8小时
          this.calculateTime(endTime, "hour", "0");
        } else if (value == "1") {
          // 1天
          this.calculateTime(endTime, "day", "0");
        } else if (value == "2") {
          // 7天
          this.calculateTime(endTime, "day7", "0");
        } else if (value == "3") {
          // 14天
          this.calculateTime(endTime, "day14", "0");
        } else if (value == "4") {
          // 30天
          this.calculateTime(endTime, "day30", "0");
        } else {
          // 60天
          this.calculateTime(endTime, "day60", "0");
        }
      }
    },
    calculateTime(timeString, unit, type) {
      const time = new Date(timeString);
      const step = {
        hour: 28800000, // 8小时
        day: 86400000, // 一天
        day7: 604800000, // 一天
        day14: 1209600000, // 一天
        day30: 2592000000, // 一天
        day60: 5184000000 // 一天
      };
      if (type == "0") {
        // 减 计算startTime
        const newTime = new Date(time.getTime() - step[unit]);
        this.form.startTime = this.formatDate(newTime);
        console.log(this.form.startTime, "this.form.startTime9999");
      } else {
        // 加 计算endtime
        const newTime = new Date(time.getTime() + step[unit]);
        this.form.endTime = this.formatDate(newTime);
      }
    },
    // 将北京时间转换为卡尔加里时间
    convertBeijingToCalgary(beijingDate) {
      const options = {
        timeZone: 'America/Edmonton',  // 卡尔加里所属时区
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false                 // 强制24小时制
      };
      // 直接生成目标格式的字符串
      const formatter = new Intl.DateTimeFormat('en-CA', options);
      const calgaryTime = formatter.format(new Date())
        .replace(/(\d{4})-(\d{2})-(\d{2}),? (\d{2}:\d{2}:\d{2})/, '$1-$2-$3 $4');
      return calgaryTime
      // const now = new Date();
      // // 获取UTC时间的毫秒数
      // const utcTime = now.getTime() + now.getTimezoneOffset() * 60000;
      // // 卡尔加里时间偏移量 (UTC-7)
      // const calgaryOffset = -7 * 60; // 以分钟为单位
      // // 计算卡尔加里时间
      // const calgaryTime = new Date(utcTime + calgaryOffset * 60000);
      // calgaryTime.setSeconds(0, 0);
      // return calgaryTime;
      // const beijingOffset = 8 * 60; // 北京时间偏移量（分钟）
      // const calgaryOffset = -6 * 60; // 卡尔加里时间偏移量（分钟）
      // const offset = calgaryOffset - beijingOffset; // 时间差（分钟）
      // const calgaryDate = new Date(beijingDate.getTime() + offset * 60000);
      //return beijingDate;
    },
    // splitTimeIntoParts(startTime, endTime) {
    //     console.log(startTime, endTime, "startTime, endTime");
    //     const totalDuration = endTime - startTime;
    //     const partDuration = totalDuration / 10;
    //     this.splitTimes = [];

    //     for (let i = 0; i < 10; i++) {
    //         const newTime = this.formatDate(
    //             new Date(startTime.getTime() + partDuration * i)
    //         );
    //         this.splitTimes.push(newTime);
    //     }
    //     // this.splitTimes.push(endTime);
    // },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date
        .getDate()
        .toString()
        .padStart(2, "0");
      const hours = date
        .getHours()
        .toString()
        .padStart(2, "0");
      const minutes = date
        .getMinutes()
        .toString()
        .padStart(2, "0");
      const seconds = date
        .getSeconds()
        .toString()
        .padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    isDateObject(value) {
      return value instanceof Date;
    },
    clickCheck() {
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      this.option.series = [];
      this.getWellTrendConfig()
    },
    clickNext() {
      if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        (this.form.startTime == "" || this.form.startTime == null) &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        (this.form.endTime == "" || this.form.endTime == null)
      ) {
        let startTime = "";
        if (this.isDateObject(this.form.startTime)) {
          startTime = this.formatDate(this.form.startTime);
        } else {
          startTime = this.form.startTime;
        }
        const time = new Date(startTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.formatDate(newTime);
      }
    },
    clickPrevious() {
      if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() - 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        (this.form.startTime == "" || this.form.startTime == null) &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() - 2592000000);

        this.form.endTime = this.formatDate(newTime);
        const time2 = new Date(this.form.endTime);
        const newTime2 = new Date(time2.getTime() - 2592000000);
        this.form.startTime = this.formatDate(newTime2);
      } else if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        (this.form.endTime == "" || this.form.endTime == null)
      ) {
        let startTime = "";
        if (this.isDateObject(this.form.startTime)) {
          startTime = this.formatDate(this.form.startTime);
        } else {
          startTime = this.form.startTime;
        }
        const time = new Date(startTime);
        const newTime = new Date(time.getTime() - 2592000000);
        this.form.startTime = this.formatDate(newTime);
      }
    },
    // TODO使用mqtt 进行优化
    // initClient() {
    //     socket.methods.disconnect();
    //     if (!socket.methods.getClientState()) {
    //         let me = this;
    //         socket.methods.connection({
    //             location: "192.168.5.90",
    //             port: 31330,
    //             topics: "dwWell", // 井列表页面
    //             successMethod: me.successMethods,
    //             errorMethod: me.errorMethods,
    //         });
    //     }
    // },

    // 保留两位小数
    formattedArr(arr) {
      return arr.map(item => {
        return parseFloat(item).toFixed(2);
      });
    },

    async twelveWells() {
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      // const parmas = {
      //     startTime: this.form.startTime,
      //     endTime: endTime,
      //     wellId: this.wellId,
      // };
      const res = await getTrendByTagType({
        startTime: this.form.startTime,
        endTime: endTime,
        wellId: this.wellId,
        tagType: 45
      });
      if (res.code === 200 && JSON.stringify(res.data) !== "{}") {
        // this.xData = Object.keys(res.data.timeList).sort(function (a, b) {
        //   return new Date(a) - new Date(b);
        // });
        if (res.data.timeList != undefined) {
          const entries = Object.entries(res.data.timeList);
          entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
          const sortedData = Object.fromEntries(entries);
          const keys = Object.keys(sortedData);
          const values = Object.values(sortedData);
          // entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
          // this.xValue = Object.values(res.data.timeList);
          this.xInterval = Math.ceil(keys.length / 10);
          this.option.xAxis[0].data = keys;
          this.option.xAxis[0].axisLabel.interval = this.xInterval;
          this.option.series[11].data = this.formattedArr(values);
          this.option.xAxis[1].data = keys;
          this.option.xAxis[1].axisLabel.interval = this.xInterval;
          this.init();
        } else {
          this.option.series[0].data = []
        }
      } else {
        this.option.series[0].data = []
      }
    },
    //导出
    async exportCheck() {
      this.exportdaochu = true;
      this.exportLoading = true;
      this.loading = true;
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      let startTime = this.form.startTime;
      let wellId = this.wellId;
      try {
        const blob = await exportEspTrend(wellId, startTime, endTime);
        exportFile(blob, 'ESP Trend', "xlsx");
      } catch (error) {
        console.error("Export failed:", error);
      } finally {
        this.exportdaochu = false;
        this.exportLoading = false;
        this.loading = false;
      }
    },
    async getEachartsValue() {
      try {
        // 并行调用所有接口
        const [
          whtData,
          tcdData,
          hzData,
          valveData,
          csgTempData,
          whpData,
          prdHeelData,
          stmHeelData,
          csgPresData,
          flowRateData,
          ampsData
        ] = await Promise.all([
          this.init()
          // this.twelveWells()
        ]);

        // 处理获取到的数据
        // ...
      } catch (error) {
        console.error("An error occurred while fetching data:", error);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .el-table__cell {
  padding: 0.22rem 0 !important;
}

:deep(.el-input__inner) {
  text-align: left !important;
}

.tip-box {
  text-align: left;
  height: 2rem;
  line-height: 2.2rem;
  color: red;
}

.page-box {
  //height: 3vh;
  //margin-top: 1.5rem;
}

.trendpad {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .add-button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 15px;
  }

  .tanchaung {
    height: 83%;
    width: 90%;
    z-index: 2000;
    position: absolute;
    background: pink;
  }

  .export_daochu {
    height: 83%;
    width: 90%;
    z-index: 2000;
    position: absolute;

    ::v-deep .el-loading-mask {
      background: rgba(0, 0, 0, 0.8);
    }
  }

  .content {
    width: 98%;
    height: 90%;
  }

  .footer {
    width: calc(100% - 1rem);
    padding: 0.7422rem 0;
    border-top: 1px solid #6f7072;
    border-bottom: 1px solid #6f7072;
    margin-top: 0.1484rem;
    display: flex;
    align-items: center;
    justify-content: space-around;
    z-index: 9999;

    .footer-item {
      color: #ffffff;
      //border: 1px solid #ff0000;
      display: flex;
      justify-content: space-between;
      flex-direction: row;
      align-items: center;
      //width: 25%;
      .el-button {

        //margin-left: -14rem;
      }

      .el-input,
      .el-select {
        :deep(.el-input__inner) {
          background-color: #121a32;
          color: #000000;
          font-size: 0.6927rem;
        }
      }

      :deep(.el-select) {
        width: 9.3325rem;
        // height: 1.4844rem;
      }

      :deep(.el-input) {
        width: 14.3325rem !important;
        height: 2.4844rem !important;
      }

      :deep(.el-button) {
        color: #ffffff !important;
      }
    }
  }

  ::v-deep .el-dialog {
    height: 42rem !important;

    .tagConfigurationBox {
      display: flex;
      flex-direction: row;
      flex: 1;
      height: 60vh;

      .left-box {
        padding-right: 0.5rem;
        width: 32%;

        .left-list-box {
          display: flex;
          height: 55vh;
          overflow: auto;
        }

        .searchBar {
          display: flex;
          flex-direction: row;
          margin-bottom: 0.5rem
        }
      }

      .right-box {
        width: 68%;

        .operationBar {
          display: flex;
          justify-content: flex-end;
          flex-direction: row;
          margin-bottom: 0.5rem;

          .left-tip {
            line-height: 2rem
          }
        }

        .right-list-box {
          display: flex;
          height: 55vh;
          overflow: auto;

          .groupItem {
            display: inline-flex;
            border-radius: 4px;
            text-align: center;
            background: #dbedff;
            padding: 0.1rem 0.2rem;
            margin-right: 0.4rem;

            ::v-deep .el-radio-button__inner {
              padding: 0.2rem 0.3rem;
            }

            .axesName {
              display: inline-block;
              height: 1.2rem;
              align-items: center;
              padding: 0.3rem 0.4rem;
              margin: 0;
            }
          }

          .gapR {
            margin-right: 10px
          }
        }
      }
    }
  }
}
</style>
